#include "timestat.h"

static const long oneMillion = 1000000;

void CTimeStat::AddStep(const string& step)
{
    struct timeval tv;
    gettimeofday(&tv,NULL);
    m_times[step] = tv;
}

double CTimeStat::GetInterval(const string& step1,const string& step2, IntervalUnit unit )
{
    map<string,timeval>::iterator it1 = m_times.find(step1);
    map<string,timeval>::iterator it2 = m_times.find(step2);

    if (it1 == m_times.end() || it2 == m_times.end())
        return 0;

    double diff = 0;
    struct timeval tmp;
    timersub(&(it1->second),&(it2->second),&tmp);
    if ( unit == UNIT_SECOND)
    {
        diff = tmp.tv_sec + tmp.tv_usec/oneMillion;
    }
    else if (unit == UNIT_USECOND)
    {
        diff = tmp.tv_sec*oneMillion + tmp.tv_usec;
    }

    return diff;
}

double CTimeStat::TimeDiff(const struct timeval& tv1,
            const struct timeval& tv2, IntervalUnit unit)
{
    double diff = 0;
    struct timeval tmp;
    timersub(&tv1,&tv2,&tmp);
    
    if ( unit == UNIT_SECOND)
    {
        diff = tmp.tv_sec + tmp.tv_usec/oneMillion;
    }
    else if (unit == UNIT_USECOND)
    {
        diff = tmp.tv_sec*oneMillion + tmp.tv_usec;
    }

    return diff;
}


